﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace 表单数据绑定
{
    /// <summary>
    /// AddUserForm.xaml 的交互逻辑
    /// </summary>
    public partial class AddUserForm : Window
    {
        public AddUserForm()
        {
            InitializeComponent();
            var vm = new AddUserFormViewModel();
            vm.RequestClose += () => this.Close();
            DataContext = vm;
        }
    }


    public class AddUserFormViewModel : INotifyPropertyChanged
    {
        private User _user = new User();

        public User User
        {
            get => _user;
            set
            {
                _user = value;
                OnPropertyChanged();
            }
        }

        public ICommand SubmitCommand { get; }
        public ICommand CancelCommand { get; }

        public event Action RequestClose;

        public AddUserFormViewModel()
        {
            SubmitCommand = new RelayCommand(_ => Submit());
            CancelCommand = new RelayCommand(_ => Cancel());
        }

        private void Submit()
        {
            // 提交逻辑,显示用户信息
            MessageBox.Show($"Name: {User.Name}\nAge: {User.Age}\nEmail: {User.Email}", "User Information");
            // 关闭窗口
            RequestClose?.Invoke();
        }

        private void Cancel()
        {
            // 取消逻辑
            // 关闭窗口
            RequestClose?.Invoke();
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string name = null)
            => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}
